/**
 * 
 */
package com.jiang.service.front.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jiang.dao.IAdminDAO;
import com.jiang.dao.IAdminLogsDAO;
import com.jiang.dao.IRoleDAO;
import com.jiang.dao.impl.AdminDAOImpl;
import com.jiang.dao.impl.AdminLogsDAOImpl;
import com.jiang.dao.impl.RoleDAOImpl;
import com.jiang.factory.DAOFactory;
import com.jiang.service.front.IAdminServiceFront;
import com.jiang.utils.ValidationUtils;
import com.jiang.vo.Admin;
import com.jiang.vo.AdminLogs;
import com.jiang.vo.Role;

/**
 * @author Administrator
 * @用户业务层实现类
 */
public class AdminServiceFrontImpl implements IAdminServiceFront {

	@Override
	public Admin find(String aid, String password) throws Exception{
		
		Admin admin = null;
		// 数据验证自动在控制层完成了，这里为了鲁棒性还是最好判断下
		if(ValidationUtils.validateEmpty(aid)&&ValidationUtils.validateEmpty(password)){
			IAdminDAO adminDAO = DAOFactory.getInstance(AdminDAOImpl.class);
			admin = adminDAO.doFind(aid, password);
		}
		return admin;
	}
	
	/**
	 * @登录方法
	 * @param aid
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String,Object> login(String aid,String password, String ip) throws Exception{
		
			Map<String,Object> resultMap = new HashMap<>();
			Admin admin = this.find(aid, password);
			if(admin != null){
				// 如果查找到了用户
				AdminLogs adminLogs = new AdminLogs();
				adminLogs.setIp(ip);
				adminLogs.setAdmin(admin);
				Date now = new Date(); // 记录当前的时间
				adminLogs.setLogindate(now);
				// 2. 记录登录日志
				IAdminLogsDAO adminLogsDAO  = DAOFactory.getInstance(AdminLogsDAOImpl.class);
				adminLogsDAO.doCreate(adminLogs);
				// 3. 修改用户最后登录时间
				IAdminDAO adminDAO = DAOFactory.getInstance(AdminDAOImpl.class);
				adminDAO.doUpdateLastDateTime(aid, now);
				// 4. 获取用户的相关的菜单权限(后台管理员才有)
				if(admin.getType() == 1){
					IRoleDAO roleDAO = DAOFactory.getInstance(RoleDAOImpl.class);
					Role role = admin.getRole();
					if(role.getRid()!=null){
						// 先塞进去权限组
						roleDAO.doFindGroupsByRole(role);
						// 再塞进去权限
						roleDAO.doFindActionsByRole(role);
					}
				}
				resultMap.put("result", true);
				resultMap.put("data", admin);
			}else{
				resultMap.put("result", false);
			}
			
			return resultMap;
	}

	@Override
	public boolean updatePassword(String aid, String oldPassword, String newPassword) throws Exception {
		
		IAdminDAO adminDAO = DAOFactory.getInstance(AdminDAOImpl.class);
		return adminDAO.doUpdatePassword(aid, oldPassword, newPassword);
		
	}
}
